package edu.ut.ece382c.valloy.inputter;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Inputter 
{
	// my3arrays[0] will be the classes_array
	// my3arrays[1] will be the virtual_functions_array
	// my3arrays[2] will be the virtual_predicates_array
	// my3arrays[3] will be the everything_else_array
	String[][] my4arrays = new String[4][];
	
	public Inputter(String filePath)
	{
		try
		{
			FileInputStream fstream = new FileInputStream(filePath);
		    DataInputStream in = new DataInputStream(fstream);
		    BufferedReader br = new BufferedReader(new InputStreamReader(in));
		    
		    //Recursive function call to collect all inputs into 4 String arrays
		    my4arrays = recursiveInputCollector(my4arrays, br);
		    in.close();
		}		
		catch (Exception e) 
		{
			System.err.println("Inputter Exception: " + e.getMessage());
		}
	}
	
	public String[][] getMy4Arrays()
	{
		return my4arrays;
	}
	
	private static String[] build(String strLine, String[] myArray, BufferedReader br) throws IOException
	{
		String[] classes_array = new String[(myArray == null) ? 1 : (myArray.length + 1)];
		if (!(myArray == null))
			System.arraycopy(myArray, 0, classes_array, 0, myArray.length);
		classes_array[(myArray == null) ? 0 : myArray.length] = strLine;
		if (!strLine.contains("}"))
		{
			do{
				strLine = br.readLine();
				classes_array[(myArray == null) ? 0 : myArray.length] += strLine + "\n";
			}while (!strLine.contains("}"));	    				
		}
		return classes_array;
	}
	
	public static String[][] recursiveInputCollector(String[][] setOfArrays, BufferedReader br) throws IOException
	{
		String strLine;
			
	    while ((strLine = br.readLine()) != null)   
	    {
	    	if (strLine.contains("class"))
	    		setOfArrays[0] = build(strLine, setOfArrays[0], br);
	    	else if(strLine.contains("virtual fun"))
	    		setOfArrays[1] = build(strLine, setOfArrays[1], br);
	    	else if(strLine.contains("virtual pred"))
	    		setOfArrays[2] = build(strLine, setOfArrays[2], br);
	    	else
	    	{
	    		if(setOfArrays[3] == null)
	    		{
	    			String[] newLine = {strLine};
	    			setOfArrays[3] = newLine;
	    		}
	    		else
	    			setOfArrays[3][0] += strLine + "\n";
	    	}
	    	return(recursiveInputCollector(setOfArrays, br));
	    }
	    return(setOfArrays);
	}
}